import React, { memo, useRef, FC } from 'react';
import { FormInstance } from 'antd/lib/form';
// import styles from './index.less';
import CommonModal from '@/components/CommonModal';
import { message } from 'antd';
import { editPassWordAPI } from '@/services/user';

const ModalContent: FC<{}> = () => {
  const changePasswordRef = useRef<FormInstance>();

  return (
    <>
      <CommonModal
        title="修改密码"
        width={500}
        type={'header-changePassword'}
        onOk={async (cancelModal: (type?: string, clear?: boolean) => void) => {
          try {
            const changePasswordFields: any = await changePasswordRef.current?.validateFields();
            const { newPassWord, repeatPassWord, oldPassWord } = changePasswordFields;
            if (newPassWord === repeatPassWord) {
              let res = await editPassWordAPI({ newPassWord, oldPassWord });
              if (res.result === 0) {
                message.success('密码修改成功！');
                cancelModal();
              }
            } else {
              message.error('两次密码输入不一致!');
            }
          } catch (errorInfo) {
            console.log('Failed:', errorInfo);
          }
        }}
      >
        <ChangePasswordForm changePasswordRef={changePasswordRef} />
      </CommonModal>
    </>
  );
};

import { useUnmount } from 'ahooks';
import ProTable, { ProColumns } from '@/components/ProTable';
import styles from './index.less';

interface Params {
  oldPassWord: string;
  newPassWord: string;
  replacePassWord: string;
}
const ChangePasswordForm: FC<{
  changePasswordRef: React.MutableRefObject<FormInstance | undefined>;
}> = ({ changePasswordRef }) => {
  useUnmount(() => {
    changePasswordRef.current?.resetFields();
  });

  const columns: ProColumns<Params>[] = [
    {
      title: '旧密码:',
      dataIndex: 'oldPassWord',
      rules: [
        {
          required: true,
        },
        {
          pattern: /^.*(?=.{6,}).*$/,
          message: '密码最少6位数',
        },
      ],
      valueType: 'password',
    },
    {
      title: '新密码:',
      dataIndex: 'newPassWord',
      rules: [
        {
          required: true,
        },
        {
          pattern: /^.*(?=.{6,}).*$/,
          message: '密码最少6位数',
        },
      ],
      valueType: 'password',
    },
    {
      title: '重复密码:',
      dataIndex: 'repeatPassWord',
      rules: [
        {
          required: true,
        },
        {
          pattern: /^.*(?=.{6,}).*$/,
          message: '密码最少6位数',
        },
      ],
      valueType: 'password',
    },
  ];
  return (
    <ProTable<Params>
      className={styles['change-password-wrap']}
      form={{ layout: 'vertical', autoComplete: 'off' }}
      columns={columns}
      type={'form'}
      formRef={changePasswordRef}
    />
  );
};

export default memo(ModalContent);
